package cn.rick.controller;

import cn.dev33.satoken.util.SaResult;
import cn.rick.entity.SysRole;
import cn.rick.entity.SysRoleMenu;
import cn.rick.entity.SysUserRole;
import cn.rick.service.ISysRoleMenuService;
import cn.rick.service.ISysRoleService;
import cn.rick.service.ISysUserRoleService;
import cn.rick.util.EasyExcelUtil;
import cn.rick.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Rick
 * @date 2022-10-21 19:01
 */
@RestController
@RequestMapping("/api/role")
@Api(value = "角色控制", tags = {"角色控制"})
public class RoleController {

    @Resource
    ISysRoleService iSysRoleService;

    @Resource
    ISysRoleMenuService iSysRoleMenuService;

    @Resource
    ISysUserRoleService iSysUserRoleService;

    @GetMapping("/getAll")
    @ApiOperation("获取所有角色")
    public SaResult getAll() {
        return SaResult.data(iSysRoleService.list());
    }

    @GetMapping("/getRolesByUserId")
    @ApiOperation("通过用户id查询拥有的角色")
    public SaResult getRolesByUserId(Long userId) {
        List<Long> roleIdsByUserId = iSysRoleService.getRoleIdsByUserId(userId);
        return SaResult.data(roleIdsByUserId);
    }

    @GetMapping("/getRolesObjByUserId")
    @ApiOperation("通过用户id查询角色对象")
    public SaResult getRolesObjByUserId(Long userId) {
        List<SysRole> rolesByUserId = iSysRoleService.findRolesByUserId(userId);
        return SaResult.data(rolesByUserId);
    }

    /**
     * 通过参数获取所有角色
     *
     * @param sysRole   角色参数
     * @param startDate 开始时间区间
     * @param endDate   结束时间区间
     * @param pageNum   当前页
     * @param pageSize  页大小
     * @return
     */
    @GetMapping("/getDataByParams")
    @ApiOperation("通过参数获取所有角色")
    public SaResult getDataByParams(SysRole sysRole, String startDate, String endDate, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(sysRole.getRoleName())) {
            wrapper.like(SysRole::getRoleName, sysRole.getRoleName());
        }
        if (StringUtils.isNotEmpty(sysRole.getRoleKey())) {
            wrapper.like(SysRole::getRoleKey, sysRole.getRoleKey());
        }
        if (StringUtils.isNotEmpty(sysRole.getStatus())) {
            wrapper.eq(SysRole::getStatus, sysRole.getStatus());
        }
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            wrapper.between(SysRole::getCreateTime, startDate, endDate + " 23:59:59");
        }

        PageHelper.startPage(pageNum, pageSize);
        List<SysRole> list = iSysRoleService.list(wrapper);
        PageInfo<SysRole> pageInfo = new PageInfo<>(list);
        return SaResult.data(pageInfo);
    }

    @GetMapping("/download")
    @ApiOperation("通过参数下载所有角色")
    public void download(SysRole sysRole, String startDate, String endDate, HttpServletResponse response) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(sysRole.getRoleName())) {
            wrapper.like(SysRole::getRoleName, sysRole.getRoleName());
        }
        if (StringUtils.isNotEmpty(sysRole.getRoleKey())) {
            wrapper.like(SysRole::getRoleKey, sysRole.getRoleKey());
        }
        if (StringUtils.isNotEmpty(sysRole.getStatus())) {
            wrapper.eq(SysRole::getStatus, sysRole.getStatus());
        }
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            wrapper.between(SysRole::getCreateTime, startDate, endDate + " 23:59:59");
        }

        List<SysRole> list = iSysRoleService.list(wrapper);
        EasyExcelUtil.writeExcel(response, list, SysRole.class, "角色信息");
    }

    @PostMapping("/saveRoleWithMenus")
    @ApiOperation("保存角色信息以及菜单")
    public SaResult saveRoleWithMenus(@RequestBody Map<String, Object> map) {
        SysRole role = JSONObject.parseObject(JSON.toJSONString(map), SysRole.class);
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getRoleName, role.getRoleName());
        SysRole one = iSysRoleService.getOne(wrapper);
        if (Objects.nonNull(one) && role.getRoleId() == null) {
            return SaResult.error("角色名已存在");
        } else {
            boolean b = iSysRoleService.saveOrUpdate(role);

            LambdaQueryWrapper<SysRoleMenu> sysRoleMenuWrapper = new LambdaQueryWrapper<>();
            sysRoleMenuWrapper.eq(SysRoleMenu::getRoleId, role.getRoleId());
            iSysRoleMenuService.remove(sysRoleMenuWrapper);
            List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
            List<Integer> ids = (List<Integer>) map.get("menuIds");
            ids.forEach(id -> {
                SysRoleMenu srm = new SysRoleMenu();
                srm.setRoleId(role.getRoleId());
                srm.setMenuId(Long.valueOf(id));
                sysRoleMenus.add(srm);
            });
            iSysRoleMenuService.saveBatch(sysRoleMenus);
            if (b) {
                return SaResult.ok("保存成功");
            } else {
                return SaResult.error("保存失败");
            }
        }
    }

    @PostMapping("/del")
    @ApiOperation("删除角色")
    public SaResult del(@RequestBody Map<String, Object> map) {
        if (Objects.nonNull(map)) {
            if (Objects.nonNull(map.get("roleId"))) {
                Integer roleId = (Integer) map.get("roleId");

                LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SysUserRole::getRoleId, roleId);
                List<SysUserRole> list = iSysUserRoleService.list(wrapper);
                if (list.size() > 0) {
                    return SaResult.error("您所删除的角色关联了[" + list.size() + "]个用户，请先取消关联");
                } else {

                    LambdaQueryWrapper<SysRoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(SysRoleMenu::getRoleId, roleId);
                    iSysRoleMenuService.remove(lambdaQueryWrapper);

                    if (iSysRoleService.removeById(roleId)) {
                        return SaResult.ok("删除成功");
                    } else {
                        return SaResult.error("删除失败，请稍后再试");
                    }

                }
            } else if (Objects.nonNull(map.get("roleIds"))) {
                List<Integer> ids = (List<Integer>) map.get("roleIds");

                LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
                wrapper.in(SysUserRole::getRoleId, ids);
                List<SysUserRole> list = iSysUserRoleService.list(wrapper);
                if (list.size() > 0) {
                    return SaResult.error("您所删除的多个角色关联了用户，请先取消关联");
                } else {

                    LambdaQueryWrapper<SysRoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.in(SysRoleMenu::getRoleId, ids);
                    iSysRoleMenuService.remove(lambdaQueryWrapper);

                    if (iSysRoleService.removeBatchByIds(ids)) {
                        return SaResult.ok("批量删除成功");
                    } else {
                        return SaResult.error("批量删除失败，请稍后再试");
                    }

                }

            } else {
                return SaResult.error("删除失败，参数出现问题");
            }
        } else {
            return SaResult.error("删除失败，参数出现问题");
        }
    }


}
